<template>
	<view class="app-content">
		<!-- 导航 -->
		<view>
			<u-navbar :title="title" :leftIconSize="0" v-if="!loading" :fixed="true" :placeholder="false">
				<view slot="left">
					<view class="u-nav-slot" v-if="daohang.list.length<=0">
						<u-icon @click="tofanhui()" name="arrow-left" size="19" ></u-icon>
						<u-line direction="column" :hairline="false" length="16" margin="0 8px" ></u-line>
						<u-icon @click="toindex()" name="home" size="20" ></u-icon>
					</view>
				</view>
			</u-navbar>
		</view>
		<view class="xiangqing">
			<view class="chatInterface">
				<view class="scroll-view" :style="emoji.visible||otherTypesMessagePanelVisible?'padding-bottom:440rpx;':''">
					<view class="all-history-loaded">
						{{allHistoryLoaded ? '已经没有更多的历史消息' : '下拉获取历史消息'}}
					</view>
					<checkbox-group @change="selectMessages">
						<!--消息记录-->
						<view v-for="(message,index) in messages" :key="message.id">
							<!--时间显示，类似于微信，隔5分钟不发言，才显示时间-->
							<view class="time-lag">
								{{renderMessageDate(message, index)}}
							</view>
							<view class="message-recalled" v-if="message.recalled">
								<view v-if="message.senderId !== currentUser.uid">{{friend.name}}撤回了一条消息</view>
								<view v-else class="message-recalled-self">
									<view>你撤回了一条消息</view>
									<span v-if="message.type === 'text' && Date.now()-message.timestamp< 60 * 1000 " @click="editRecalledMessage(message.payload.text)">重新编辑</span>
								</view>
							</view>
							<view class="message-item" v-else>
								<view class="message-item-checkbox">
									<checkbox v-show="messageSelector.visible && message.status !== 'sending'" :value="message.id" :checked="messageSelector.messages.includes(message)" />
								</view>
								<view class="message-item-content" :class="{'self' : message.senderId ===  currentUser.uid}">
									<view class="avatar">
										<image :src="message.senderId === currentUser.uid? currentUser.avatar : friend.avatar"></image>
									</view>
									<view class="content" @longpress="showActionPopup(message)">
										<view class="message-payload" :class="message.senderId ===  currentUser.uid?'self rightsj':'leftsj'">
											<b class="pending" v-if="message.status === 'sending'"></b>
											<b class="send-fail" v-if="message.status === 'fail'"></b>
											<view v-if="message.type === 'text'" v-html="renderTextMessage(message)"></view>
											<image class="image-content" v-if="message.type === 'image'" :src="message.payload.url" :data-url="message.payload.url" @click="showImageFullScreen" mode="widthFix"></image>
											<view class="video-snapshot"  v-if="message.type === 'video'" :data-url="message.payload.video.url" @click="playVideo">
												<image :src="message.payload.thumbnail.url" mode="aspectFit"></image>
												<view class="video-play-icon"></view>
											</view>
											<ChatAudioPlayer v-if="message.type ==='audio'" :src="message.payload.url" :duration="message.payload.duration" />
											<view class="custom-message" v-if="message.type === 'order'">
												<view class="title">
													<image src="/static/images/order.png"></image>
													<text>自定义消息</text>
												</view>
												<view class="custom-message-item">编号：{{message.payload.number}}</view>
												<view class="custom-message-item">商品: {{message.payload.goods}}</view>
												<view class="custom-message-item">金额: {{message.payload.price}}</view>
											</view>
										</view>
										<view v-if="message.senderId === currentUser.uid" :class="message.read ?'message-read':'message-unread'">
											<view v-if="message.status === 'success'">{{message.read?'已读':'未读'}}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</checkbox-group>
				</view>
				<view class="action-box" v-if="!videoPlayer.visible && !messageSelector.visible">
					<view class="action-top">
						<view :class="[audio.visible ? 'record-icon record-open':'record-icon']" @click="switchAudioKeyboard"></view>
						<view class="record-input" @touchstart="onRecordStart" @touchend="onRecordEnd" v-if="audio.visible" >{{audio.recording ? '松开发送' : '按住录音'}}</view>
						<view class="message-input" v-else >
							<textarea type="text" maxlength="700" auto-height placeholder="发送消息" v-model="content" :hold-keyboard="true" confirm-type="send" @confirm="createTextMessage" @focus="messageInputFocusin" />
						</view>
						<view class="file-icon emoji-icon" @click="showEmoji"></view>
						<view class="file-icon more-icon" @click="showOtherTypesMessagePanel"></view>
						<span class="send-message-btn" @click="createTextMessage">发送</span>
					</view>
					<!--展示表情列表-->
					<view class="action-bottom action-bottom-emoji" v-if="emoji.visible">
						<image class="emoji-item" v-for="(emojiItem, emojiKey, index) in emoji.map" :key="index" :src="emoji.url + emojiItem" @click="chooseEmoji(emojiKey)"></image>
					</view>
					<!--其他类型消息面板-->
					<view class="action-bottom action-flex" v-if="otherTypesMessagePanelVisible">
						<view class="more-item" @click="createImageMessage">
							<image src="/static/images/tupian.png"></image>
							<text>图片</text>
						</view>
						<view class="more-item" @click="createVideoMessage">
							<image src="/static/images/shipin.png"></image>
							<text>视频</text>
						</view>
					</view>
				</view>
				<view class="action-popup" @touchmove.stop.prevent v-if="actionPopup.visible">
					<view class="layer"></view>
					<view class="action-box">
						<view class="action-item" @click="copy(messageSelector.messages[0].payload.text);actionPopup.visible = false;">复制</view>
						<view class="action-item" @click="deleteSingleMessage">删除</view>
						<view class="action-item" v-if="actionPopup.recallable" @click="recallMessage">撤回</view>
						<view class="action-item" @click="showCheckBox">多选</view>
						<view class="action-item" @click="actionPopup.visible = false">取消</view>
					</view>
				</view>
				<view class="messageSelector-box" v-if="messageSelector.visible">
					<view class="msgxzbtn w50" style="border-right: 1px solid #fff;" @click="messageSelector.visible = false" >
						取消
					</view>
					<view class="msgxzbtn w50 red" @click="deleteMultipleMessages" >
						删除
					</view>
				</view>
				<view class="record-loading" v-if="audio.recording"></view>
				<video v-if="videoPlayer.visible" :src="videoPlayer.url" id="videoPlayer" @fullscreenchange="onVideoFullScreenChange"></video>
				<CustomMessage v-if="customMessageFormVisible" @createCustomMessage="createCustomMessage" @closeCustomMessageForm="closeCustomMessageForm"></CustomMessage>
			</view>
		</view>
		<u-tabbar v-if="daohang.list.length>0" :zIndex="999" :value="daohang.naviKey" :activeColor="daohang.navi_set.active_color" :inactiveColor="daohang.navi_set.inactive_color">
			<u-tabbar-item v-for="(item,index) in daohang.list" :badge="item.badge" :key="index" :text="item.text" :icon="daohang.naviKey==index?item.selectedIconPath:item.iconPath" @click="tabClick(item,index)" ></u-tabbar-item>
		</u-tabbar>
		<u-no-network @disconnected="disconnected" ></u-no-network>
		<u-toast ref="uToast" />
		<view class="km_loading" v-if="loading">
			<image src="@/static/loading_3.gif" mode=""></image>
		</view>
	</view>
</template>

<script>
	import { wappConfig } from "@/api/api.js";
	import { chatApi,userApi } from "@/api";
	import { toLogin } from '@/libs/login';
	import EmojiDecoder from '@/libs/EmojiDecoder';
	import ChatAudioPlayer from '@/components/ChatAudioPlayer/ChatAudioPlayer';
	const recorderManager = uni.getRecorderManager();
	export default {
		data() {
			return {
				title: 'KMLOVE',
				loading:true,
				config:{},
				pagePath:'/views/chat/index',
				daohang:{
					list:[],
					naviKey:0,
					navi_set:{
						active_color: "#34C083",
						height: 100,
						inactive_color: "#757575",
					}
				},
				user:{},
				goeasylj:false,
				uid:10001,
				//消息记录
				messages: [],
				//聊天文本框
				content: '',
				//定义表情列表
				emoji : {
					url : '',
					map : null,
					visible: false,
					decoder:  null,
				},
				friend: {uid:""},//聊天用户
				currentUser:{uid:""},//用户
				//是否加载完所有历史消息
				allHistoryLoaded: false,
				//是否展示‘其他消息类型面板’
				otherTypesMessagePanelVisible: false,
				audio : {
					startTime: null,
					//语音录音中
					recording : false,
					//录音按钮展示
					visible : false
				},
				
				videoPlayer : {
					visible : false,
					url : '',
					context : null
				},
				// 展示自定义消息框
				customMessageFormVisible: false,
				
				// 展示消息删除弹出框
				actionPopup:{
					visible: false,
					message: null,
				    recallable: false,
				},
				// 消息选择
				messageSelector: {
					visible: false,
					messages: []
				},
				initshow:false,
				pages:{
					isAll:false,
					pno:1
				},
			}
		},
		components: {
			ChatAudioPlayer
		},
		onReady () {
			this.videoPlayer.context = uni.createVideoContext('videoPlayer',this);
		},
		onLoad(e) {
			if(e.scene){
				let et = decodeURIComponent(e.scene)
				  console.log(et)
				  let theRequest = new Object();
				  let strs = et.split("&");
				  for(let i = 0; i < strs.length; i++) {
				    theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
				  }
				  e=theRequest;
			}
			if(e.id){
				this.uid=e.id;
				this.friend.uid=e.id;
				this.getconfig();
				this.gethomeuserdetail();
			}else{
				this.loading=false;
				uni.showToast({
					icon:"error",
					title: '非法进入!!!',
					duration:2300,
					success(res) {
						console.log(res)
					},
					fail(err) {
						console.log(err)
					}
				})
				setTimeout(() => {
					uni.navigateBack({
					delta: 1,
					fail(){
					 uni.reLaunch({
						 url: '/pages/index/index'
					 });
					}
					});
				}, 2000)
			}
		},
		onShow() {
			if(this.initshow){
				this.getuser();
			}
			// console.log(this.$util.)
		},
		onHide() {
			// this.goeasydisconnect()
			this.sendChatOut();
		},
		onUnload(){
			// this.goeasydisconnect()
			// //退出聊天页面之前，清空监听器
			// this.goeasy.im.on(GoEasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, ()=>{});
			// this.goeasy.im.on(GoEasy.IM_EVENT.MESSAGE_DELETED, ()=>{});
			this.sendChatOut();
		},
		onPullDownRefresh(e) {
			// this.loadHistoryMessage(false);
			let pg=this.pages,that=this;
			if(!this.allHistoryLoaded){
				// this.getchatgoeasylist()
				if(pg.pno<pg.pageCount){
					that.getChatDetailsList(parseInt(pg.pno)+1);
				}else{
					that.allHistoryLoaded = true;
					setTimeout(() => {
						uni.stopPullDownRefresh();
					}, 2000)
				}
			}
		},
		methods: {
			// 退出聊天
			sendChatOut(){
				let t=this;
				t.socketSend("chatOut");
			},
			// 连接聊天
			sendChatConnect(){
				let t=this;
				t.socketSend("chatConnect");
			},
			socketSend(type){
				if(!type){
					return false;
				}
				// console.log(type)
				let t=this;
				t.$socket.send({
					type:"message",
					userId: t.user.uid,
					data:{
						type:type?type:"chatConnect",
						senderId:t.user.uid,
						receiverId:t.friend.uid,
					}
				})
				.then(arr=>{
					console.log('成功',arr);
				})
				.catch(error=>{
					console.log("失败",error);
				});
			},
			copy(e){
				console.log(e)
				uni.setClipboardData({
				      data: e,
				      success(res) {
				        wx.showToast({
				          title: '复制成功',
				          icon: 'none'
				        })
				      }
				    })
			},
			gethomeuserdetail(lat="",lng=""){
				let t=this;
				userApi("userDetail/"+this.uid,{}).then(res=>{
					t.friend=res.data;
					t.title=res.data.nickName;
					t.loading=false;
				}).catch(res => {
					console.log(res)
					uni.showModal({
						content:res.msg?res.msg:res?res:"获取用户失败",
						title:"提示",
						showCancel:false
					})
					t.loading=false;
				});
			},
			// 建立连接
			getChatInIt(){
				let t=this;
				// 聊天连接
				t.sendChatConnect();
				// 获取聊天记录
				t.getChatDetailsList();
				// 聊天监听
				t.initialChatListeners();
				// that.loadHistoryMessage(true);
				// 录音监听器
				t.initRecorderListeners();
				
				// 标记已读
				// t.markPrivateMessageAsRead()
			},
			// 聊天监听
			initialChatListeners() {
				// 监听私聊消息
				let t=this;
				t.$socket.on('chat', (res) => {
					let message=res.data;
					console.log(t.friend.uid,message.receiverId)
					if(t.friend.uid==message.receiverId){
						return false;
					}
					console.log(message)
					let senderId = message.senderId;
					let receiverId = message.receiverId;
					let friendId = t.currentUser.uid == senderId?receiverId:senderId;
					if (friendId === t.friend.uid) {
						if(t.messages.length>0){							
							t.messages.push(message);
							//聊天时，收到消息标记为已读
							t.markPrivateMessageAsRead();
							//收到新消息，是滚动到最底部
							t.scrollToBottom();
						}else{
							t.messages=message;
						}
					}
				})
				//监听消息撤回
				t.$socket.on('recalledChat', (res) => {
					let recalledMessages=res.data;
					recalledMessages.forEach(message => {
						let senderId = message.senderId;
						let receiverId = message.receiverId;
						let friendId = t.currentUser.uid === senderId?receiverId:senderId;
						if (friendId === t.friend.uid) {
							for(let i in t.messages){
								if(t.messages[i].id==message.id){
									t.messages[i].recalled=true;
								}
							}
						}
					});
				})
				// 监听消息已读
				t.$socket.on('readChat', (res) => {
					let readMessages=res.data;
					readMessages.forEach(message => {
						let senderId = message.senderId;
						let receiverId = message.receiverId;
						let friendId = t.currentUser.uid === senderId?receiverId:senderId;
						if (friendId === t.friend.uid) {
							for(let i in t.messages){
								if(t.messages[i].id==message.id){
									t.messages[i].read=true;
								}
							}
						}
					});
				})
			},
			sendMessage(message){
				console.log(message)
				let t=this;
				uni.showLoading({title:"发送中..."});
				chatApi("sendMessage",message).then(res=>{
					let msg=res.data;
					t.messages.push(msg);
					//收到新消息，是滚动到最底部
					t.scrollToBottom();
					uni.showToast({
						title:res.msg,
						icon:"none",
						duration:2500
					})
					// uni.hideLoading();
				})
				.catch(res => {
					console.log(res)
					uni.hideLoading();
					uni.showModal({
						content:res.msg?res.msg:res?res:"失败",
						title:"提示",
						showCancel:false
					})
				});
			},
			createTextMessage() {
				if (this.content.trim() !== '') {
					let textMessage={
						type: 'text',
						chattype: '1',
						senderId:this.currentUser.uid,
						receiverId:this.friend.uid,
						payload:{
							text:this.content
						}
					}
					this.sendMessage(textMessage);
				}
				this.content = '';
			},
			selectMessages (e) {
				const selectedids = e.detail.value;
				let selectedMessages = [];
				this.messages.forEach(message => {
					if(selectedids.includes(message.id)){
						selectedMessages.push(message);
					}
				})
				this.messageSelector.messages = selectedMessages;
			},
			// 消息标记为已读
			markPrivateMessageAsRead () {
				let t=this;
				t.socketSend("chatMarkRead");
			},
			//渲染文本消息，如果包含表情，替换为图片
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderTextMessage(message) {
				let text=message.payload.text;
				if(message.senderId==this.user.uid){
					if(message.payload.oldtext){
						text=message.payload.oldtext;
					}
				}
				return '<span class="text-content">' + this.emoji.decoder.decode(text) + '</span>'
			},
			//像微信那样显示时间，如果有几分钟没发消息了，才显示时间
			//todo:本不需要该方法，可以在标签里完成，但小程序有兼容性问题，被迫这样实现
			renderMessageDate(message, index) {
				if (index === 0) {
					return this.formatDate(message.timestamp)
				} else {
					if (message.timestamp - this.messages[index - 1].timestamp > 5 * 60 * 1000) {
						return this.formatDate(message.timestamp)
					}
				}
				return '';
			},
			initRecorderListeners(){
				// 监听录音开始
				recorderManager.onStart(() => {
					this.audio.recording = true;
					this.audio.startTime = Date.now();
				});
				//录音结束后，发送
				recorderManager.onStop((res) => {
					let t=this;
					let endTime = Date.now();
					this.audio.recording = false;
					let duration = endTime - this.audio.startTime;
					if (duration < 1000) {
						uni.showToast({
							icon: 'error',
							title: '录音时间太短',
							duration: 500
						});
						return;
					}
					res.duration = duration;
					console.log(res)
					// let audioMessage = this.goeasy.im.createAudioMessage({
					// 	to : {
					// 		id : this.friend.uid,
					// 		type : GoEasy.IM_SCENE.PRIVATE,
					// 		data : {
					// 			name:this.friend.name,
					// 			avatar:this.friend.avatar
					// 		}
					// 	},
					// 	file: res,
					// 	onProgress :function (progress) {
					// 		console.log(progress)
					// 	},
					// 	notification : {
					// 		title : this.currentUser.name + '发来一段语音',
					// 		body : '[语音消息]'		// 字段最长 50 字符
					// 	}
					// });
					return false;
					t.$util.uploadfileOne(2,t.config.uploadUrl,res.tempFile).then(r=>{
						console.log(r)
						uni.hideLoading()
						let audioMessage={
							type: 'video',
							chattype: '1',
							senderId:t.currentUser.uid,
							receiverId:t.friend.uid,
							payload:r.chat
						}
						t.sendMessage(audioMessage);
					}).catch(res=>{
						uni.hideLoading()
					})
				});
				// 监听录音报错
				recorderManager.onError((res) =>{
					this.audio.recording = false;
					recorderManager.stop();
					uni.showToast({
						icon: 'none',
						title: '录音失败,请检查麦克风权限',
						duration: 1000
					});
				})
			},
			// 滚动到最底部
			scrollToBottom () {
				setTimeout(() => {
					uni.pageScrollTo({
						scrollTop: 2000000,
						duration: 0
					})
				},500);
			},

			retry(){
				this.getconfig();
			},
			tourl(e){
				console.log(e)
				if(!e){
					return true;
				}
				if(e==this.pagePath){
					return true;
				}
				uni.navigateTo({
					url:e,
					fail(error) {
						console.log(error)
						uni.showToast({
							title:"跳转出错",
							icon:"none"
						})
					}
				})
			},
			tofanhui(){
				console.log(1)
				uni.navigateBack({
					delta: 1,
					fail(){
						 uni.reLaunch({
							 url: '/pages/index/index'
						 });
					}
				})
			},
			toindex(){
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},
			// 切换导航
			tabClick(e,i){
				if(this.daohang.naviKey!=i){
					uni.reLaunch({
						url:e.pagePath,
						fail(err) {
							uni.showModal({
								content:err.errMsg,
								title:"错误提示",
								showCancel:false,
								fail(r) {
									console.log(r)
								}
							})
							console.log(err)
						}
					})
				}
				
			},
			getconfig(){
				let that=this;
				wappConfig({pagePath:that.pagePath}).then(e=>{
					that.daohang=e.data.naviList;
					that.config=e.data;
					that.emoji= {
						url : e.data.emoji.emojiUrl,
						map : e.data.emoji.emojiMap,
						visible: false,
						decoder:  new EmojiDecoder(e.data.emoji.emojiUrl, e.data.emoji.emojiMap),
					};
					// that.goeasyInit();
					if(!that.initshow){
						that.initshow=true;
						that.getuser();
					}
				})
				.catch(res => {
					console.log(res)
					uni.showModal({
						content:res.msg?res.msg:res?res:"获取配置文件失败",
						title:"提示",
						showCancel:false
					})
					that.loading=false;
				});
			},
			getuser(){
				console.log("isLogin：",this.$store.getters.isLogin)
				if(this.$store.getters.isLogin){
					console.log(this.$store.getters.userInfo)
					this.user=this.$store.getters.userInfo;
					this.currentUser=this.$store.getters.userInfo;
					this.getChatInIt();
				}else{
					toLogin()
				}
			},
			// 获取聊天记录
			getChatDetailsList(pno){
				let that=this;
				let list=this.messages;
				if(!pno){
					pno=1;
					list=[];
				}
				let dt={
					pages:{
						pno:pno,
						pageSize:20,
					},
					receiverId:this.uid,
					senderId:this.user.uid,
					chattype:1
				}
				chatApi('chatDetailsList',dt).then(res=>{
					console.log(res)
					uni.stopPullDownRefresh();
					let messages = res.data.list;
					if (pno==1) {
						that.scrollToBottom();
						//收到的消息设置为已读
						that.markPrivateMessageAsRead();
						that.messages = messages
					}else{
						that.messages = messages.concat(that.messages);
					}
					that.pages=res.data.pages;
					that.loading=false;
				}).catch(e=>{
					//TODO handle the exception
					console.log(e)
					that.loading=false;
				})
			},
			// 显示撤回消息按钮
			showActionPopup(message) {
				const MAX_RECALLABLE_TIME = 3 * 60 * 1000; //3分钟以内的消息才可以撤回
				this.messageSelector.messages = [message];
				if ((Date.now() - message.timestamp) < MAX_RECALLABLE_TIME && message.senderId === this.currentUser.uid && message.status === 'success') {
					this.actionPopup.recallable = true;
				} else {
					this.actionPopup.recallable = false;
				}
				this.actionPopup.visible = true;
			},
			deleteSingleMessage(){
				uni.showModal({
					content: '确认删除？',
					success: (res) => {
						this.actionPopup.visible = false;
						if (res.confirm) {
							this.deleteMessage();
						}
					},
				})
			},
			deleteMultipleMessages(){
				if (this.messageSelector.messages.length > 0) {
					uni.showModal({
						content: '确认删除？',
						success: (res) => {
							this.messageSelector.visible = false;
							if (res.confirm) {
								this.deleteMessage();
							}
						},
					})
				}
			},
			deleteMessage() {
				let that=this;
				that.messageSelector.messages.forEach(message => {
					console.log(message)
					let index = that.messages.indexOf(message);
					if (index > -1) {
						that.messages.splice(index, 1);
					}
					let dt={
						id:message.id,
						isdel:'1',
					}
					that.upDataFun(dt);
					// console.log(dt)
				});
				that.messageSelector.messages = [];
			},
			upDataFun(dt){
				if(!dt){
					return false;
				}
				chatApi("upChatDetails",dt).then(res=>{
					console.log(res)
				})
				.catch(error=>{
					console.error(error)
				})
			},
			recallMessage() {
				this.actionPopup.visible = false;
				let t=this;
				let dt={
					id:t.messageSelector.messages[0].id,
					recalled:1,
				}
				// console.log(dt)
				for(let i in t.messages){
					if(t.messages[i].id==dt.id){
						t.messages[i].recalled=true;
					}
				}
				t.upDataFun(dt);
			},
			editRecalledMessage (content) {
				if (this.audio.visible) {
					this.audio.visible = false;
				}
				this.content = content;
			},
			showCheckBox () {
				this.messageSelector.messages = [];
				this.messageSelector.visible = true;
				this.actionPopup.visible = false;
			},

			//语音录制按钮和键盘输入的切换
			switchAudioKeyboard() {
				this.audio.visible = !this.audio.visible;
				if(uni.authorize){
					uni.authorize({
						scope : 'scope.record',
						fail: () => {
							uni.showModal({
								title: '获取录音权限失败',
								content : '请先授权才能发送语音消息！'
							});
						}
					});
				}
			},
			onRecordStart () {
				try{
					recorderManager.start();
				}catch(e){
					//#ifdef H5
					uni.showToast({
						title:"h5不支持发送语音",
						icon:"none"
					})
					return false;
					//#endif
					uni.showModal({
						title: '录音错误',
						content : '请在app和小程序端体验录音，Uni官方明确H5不支持getRecorderManager, 详情查看Uni官方文档'
					});
				}
			},
			onRecordEnd () {
				try{
					recorderManager.stop();
				}catch(e){
					console.log(e);
				}
			},
			createVideoMessage () {
				let t=this;
				uni.chooseVideo({
					success : (res) => {
						// console.log(res)
						// return;
						uni.showLoading({
							title:"视频上传中..."
						})
						t.$util.uploadfileOne(2,t.config.uploadUrl,res.tempFile).then(r=>{
							console.log(r)
							uni.hideLoading()
							let videoMessage={
								type: 'video',
								chattype: '1',
								senderId:t.currentUser.uid,
								receiverId:t.friend.uid,
								payload:r.chat
							}
							t.sendMessage(videoMessage);
						}).catch(res=>{
							uni.hideLoading()
						})
					}
				})
			},
			createImageMessage() {
				let t=this;
				uni.chooseImage({
			        count : 9,
					success: (res) => {
						uni.showLoading({
							title:"图片上传中..."
						})
						t.$util.uploadFile(1,t.config.uploadUrl,res.tempFiles).then(r=>{
							uni.hideLoading()
							r.forEach(item=>{
								console.log(item)
								let textMessage={
									type: 'image',
									chattype: '1',
									senderId:t.currentUser.uid,
									receiverId:t.friend.uid,
									payload:item.chat
								}
								t.sendMessage(textMessage);
							})
						}).catch(res=>{
							uni.hideLoading()
						})
					}
				});
			},
			showImageFullScreen (e) {
				let imagesUrl = [e.currentTarget.dataset.url];
				uni.previewImage({
					urls: imagesUrl
				});
			},
			playVideo (e) {
				this.videoPlayer.visible = true;
				this.videoPlayer.url = e.currentTarget.dataset.url;
				this.$nextTick(() => {
					this.videoPlayer.context.requestFullScreen({
						direction : 0
					});
					this.videoPlayer.context.play();
				});
			},
			onVideoFullScreenChange (e) {
				//当退出全屏播放时，隐藏播放器
				if(this.videoPlayer.visible && !e.detail.fullScreen){
				    this.videoPlayer.visible = false;
				    this.videoPlayer.context.stop();
				}
			},
			messageInputFocusin () {
				this.otherTypesMessagePanelVisible = false;
				this.emoji.visible = false;
			},
			showEmoji () {
				this.emoji.visible = !this.emoji.visible;
				this.otherTypesMessagePanelVisible = false;
				this.scrollToBottom();
			},
			showOtherTypesMessagePanel () {
				this.otherTypesMessagePanelVisible = !this.otherTypesMessagePanelVisible;
				this.emoji.visible = false;
				this.scrollToBottom();
			},
			chooseEmoji (emojiKey) {
				this.content +=emojiKey;
			},
		}
	}
</script>

<style>
	 @import url('@/static/style/chatInterface.css');
	 page{
		 background:#f3f4f6;
	 }
	 .w50{
		 width: 50%;
	 }
	 .msgxzbtn{
		 text-align: center;
		 line-height: 80rpx;
	 }
	 .red{
		 color: #fa3534;
	 }
</style>
